package com.situ.car.controller;

import com.situ.car.pojo.entity.Admin;
import com.situ.car.pojo.entity.Permission;
import com.situ.car.pojo.entity.Role;
import com.situ.car.pojo.query.AdminQuery;
import com.situ.car.pojo.vo.AdminVo;
import com.situ.car.pojo.vo.RoleVo;
import com.situ.car.service.IAdminService;
import com.situ.car.service.IPermissionService;
import com.situ.car.service.IRoleService;
import com.situ.car.service.Impl.AdminServiceImpl;
import com.situ.car.service.Impl.PermissionServiceImpl;
import com.situ.car.service.Impl.RoleServiceImpl;
import com.situ.car.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@WebServlet("/admin")
public class AdminController extends BaseController{
    private IAdminService adminService = new AdminServiceImpl();
    private IRoleService roleService = new RoleServiceImpl();
    private IPermissionService permissionService = new PermissionServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("AdminController.service");
        String method = req.getParameter("method");
        switch (method) {
            case "login":
                login(req, resp);
                break;
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "selectById":
                selectById(req, resp);
                break;
            case "selectByInfoId":
                selectByInfoId(req, resp);
                break;
            case "selectAccount":
                selectAccount(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "updateInfo":
                updateInfo(req, resp);
                break;
            case "updatePassword":
                updatePassword(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "updateStatus":
                updateStatus(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
        }
    }

    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("AdminController.updatePassword");
        String id = req.getParameter("id");
        Admin admin = adminService.selectPassword(Integer.parseInt(id));
        String password = req.getParameter("password");
        String newPassword = req.getParameter("newPassword");
        System.out.println(admin);
        System.out.println(admin.getPassword());
        System.out.println(password);
        if (Objects.equals(admin.getPassword(), password)) {
            adminService.updatePassword(Integer.parseInt(id), newPassword);
            toJSON(resp, Result.ok("修改成功！请重新登录"));
            HttpSession session = req.getSession();
            session.removeAttribute("admin");
            session.removeAttribute("roleVos");
            Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
            //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
            if (cookie != null) {
                //设置Cookie的存活时间为0
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        } else {
            toJSON(resp, Result.error("原密码错误！"));
        }
    }

    private void selectAccount(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.selectByAccount");
        String id = req.getParameter("id");
        Admin admin = adminService.selectAccount(Integer.parseInt(id));
        toJSON(resp, Result.ok(admin));
    }

    private void updateInfo(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.updateInfo");
        Admin admin = MyBeanUtils.copyToBean(req, Admin.class);
        int adminPD = adminService.updateInfo(admin);
        HttpSession session = req.getSession();
        System.out.println(adminPD);
        if (adminPD != 0) {
            toJSON(resp, Result.ok("修改成功！"));
            session.setAttribute("admin", admin);
        } else {
            toJSON(resp, Result.error("账号已经存在！"));
        }
    }

    private void selectByInfoId(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.selectByInfoId");
        String id = req.getParameter("id");
        Admin admin = adminService.selectByInfoId(Integer.parseInt(id));
        toJSON(resp, Result.ok(admin));
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("admin");
        session.removeAttribute("roleVos");
        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
        if (cookie != null) {
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
        toJSON(resp, Result.ok("退出成功"));
//        resp.sendRedirect("/page/login");
    }

    private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.updateStatus");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        adminService.updateStatus(Integer.parseInt(id), Integer.parseInt(status));
        toJSON(resp, Result.ok("修改成功！"));
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.add");
        AdminVo adminVo = MyBeanUtils.copyToBean(req, AdminVo.class);
        Integer accountCount = adminService.selectByAccount(adminVo);
        if (accountCount == 0) {
            adminService.add(adminVo);
            adminService.addRole(adminVo);
            toJSON(resp, Result.ok("注册成功！"));
        } else {
            toJSON(resp, Result.error("账号已经存在！"));
        }

    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.selectById");
        String id = req.getParameter("id");
        AdminVo adminVo = adminService.selectById(Integer.parseInt(id));
        List<Role> role = roleService.selectAll();
        System.out.println(role);
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", adminVo);
        map.put("role", role);
        toJSON(resp, Result.ok(map));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.update");
        AdminVo adminVo = MyBeanUtils.copyToBean(req, AdminVo.class);
        int adminPD = adminService.update(adminVo);
        System.out.println(adminPD);
        if (adminPD != 0) {
            adminService.updateAR(adminVo);
            toJSON(resp, Result.ok("修改成功！"));
        } else {
            toJSON(resp, Result.error("账号已经存在！"));
        }

    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.deleteById");
        String id = req.getParameter("id");
        adminService.deleteById(Integer.parseInt(id));
        toJSON(resp, Result.ok("删除成功！"));
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.deleteById");
        String[] ids = req.getParameterValues("ids[]");
        if(!ObjectUtils.isEmpty(ids)) {
            adminService.deleteAll(ids);
            toJSON(resp, Result.ok("删除成功！"));
        } else {
            toJSON(resp, Result.error("没有数据要删除！"));
        }
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.selectByPage");
        AdminQuery adminQuery = MyBeanUtils.copyToBean(req, AdminQuery.class);
        PageInfo pageInfo = adminService.selectByPage(adminQuery);
        toJSON(resp, pageInfo);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminController.login");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            toJSON(resp, Result.error("验证码错误"));
            return;
        }
        Admin admin = adminService.login(account, password);
        if (admin == null) {
            JSONUtil.toJSON(resp, Result.error("用户名或密码错误"));
        }
        if (admin.getStatus() == 0) {
            toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
            return;
        }
        //自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin", admin.getAccount() + "&" + admin.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7);//设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            resp.addCookie(cookie);
        }
        session.setAttribute("admin", admin);
        AdminVo adminVo = adminService.selectRole(account);
        List<RoleVo> roleVos = permissionService.selectPath(adminVo.getRoleId());
        session.setAttribute("roleVos", roleVos);
        JSONUtil.toJSON(resp, Result.ok("登录成功"));
    }
}
